import nProgress from 'nprogress'
import router, { asyncRouter } from './router'
import store from './store'
import defaultSettings from '@/utils/get-page-title'
import 'nprogress/nprogress.css'
router.beforeEach(async(to, from, next) => {
  const whiteList = ['/login', '/404']
  // console.log(to);
  // console.log(from);
  document.title = defaultSettings(to.meta.title)
  nProgress.start()
  if (to.path === '/login' && store.state.user.token) return next('/')
  if (whiteList.includes(to.path)) return next()
  if (!store.state.user.token) return next('/login')
  // console.log(to.path)
  // const string = router.currentRoute.fullPath
  // console.log(string.indexOf('url'))
  // if (string.indexOf('url') > 0) {
  //   string = encodeURIComponent(string)
  // }
  if (!store.state.user.userInfo.userId) {
    await store.dispatch('user/getUserInfo')
    const menus = store.state.user.userInfo.roles.menus || []
    const filterRouter = asyncRouter.filter(item => {
      return menus.includes(item.children[0].name)
    })
    store.commit('menus/getMenus', filterRouter)
    router.addRoutes(store.state.menus.menusList)
    router.addRoutes([{ path: '*', redirect: '/404', hidden: true }])
    next({ ...to, replace: true })
    console.log('menus', filterRouter)
  } else {
    next()
  }
})
// console.log(to);
router.afterEach(() => {
  nProgress.done()
  // next()
})
